package logger

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"io"
	"kubehark/kubehark-framwork/pkg/Log"
	"kubehark/kubehark-framwork/pkg/Plugin/Plugins"
	"net/http"
	"time"
)

// ReadCloser comment lint rebel
type ReadCloser struct {
	rc io.ReadCloser
	w  io.Writer
}

// Read comment lint rebel
func (rc *ReadCloser) Read(p []byte) (n int, err error) {
	n, err = rc.rc.Read(p)
	if n > 0 {
		if n, err := rc.w.Write(p[:n]); err != nil {
			return n, err
		}
	}
	return n, err
}

// Close comment lint rebel
func (rc *ReadCloser) Close() error {
	return rc.rc.Close()
}



type LoggerPlugin struct {
}

func (this *LoggerPlugin) SetConfigFromInterface(data interface{}) Plugins.PluginInterface {
	Log.Setup()
	// 暂时不需要 配置文件
	return &LoggerPlugin{}
}
func (this *LoggerPlugin) RunPlugin(c *gin.Context) error {
	c.Set("startTime", time.Now())
	body := ""
	if c.Request.Method == http.MethodPost ||
		c.Request.Method == http.MethodPut ||
		c.Request.Method == http.MethodPatch {
		var buf bytes.Buffer
		newBody := &ReadCloser{c.Request.Body, &buf}
		c.Request.Body = newBody
		c.Next()
		body = buf.String()
	} else {
		c.Next()
	}
	logrus.WithContext(c).Info(body)
	return nil
}
